/**
 * Created by LaoXu on 2017/12/20.
 * @description:数据库连接池
 */
const mysql = require("mysql");
const codeObj = require('../constants/codeCons');

var pool = mysql.createPool({
    port: '3306',
    host: 'localhost',
    database: 'sousou',
    user: 'root',
    password: '123456',
    connectionLimit: 10
});

/**
 * 查询数据
 * @param sql sql语句
 * @param callback
 */
var querySQL = function (sql, callback) {
    callback = callback || function () {
        };
    pool.getConnection(function (err, connection) {
        if (err) {
            // callback({code: codeObj.error, datas: "数据库连接异常"});
            callback(codeObj.createCodeObj(codeObj.ERROR, "数据库连接异常"));
            throw err
        }

        connection.query(sql, function (err, results) {
            connection.release();
            if (err) {
                callback(codeObj.createCodeObj(codeObj.ERROR, "数据库连接异常"));
                throw err;
            } else {
                callback(codeObj.createCodeObj(codeObj.SUCCESSFUL, results));
            }
        });
    });
}

/**
 * 执行对应的SQL语句
 * @param sql sql语句
 * @param params 数组参数
 * @param callback
 */
var execSQL = function (sql, params, callback) {
    callback = callback || function () {
        };
    pool.getConnection(function (err, connection) {
        if (err) {
            // callback({code: codeObj.error, datas: "数据库连接异常"});
            callback(codeObj.createCodeObj(codeObj.ERROR, "数据库连接异常"));
            throw err
        }

        connection.query(sql, params, function (err, results) {
            connection.release();
            if (err) {
                callback(codeObj.createCodeObj(codeObj.ERROR, "数据库连接异常"));
                throw err;
            } else {
                callback(codeObj.createCodeObj(codeObj.SUCCESSFUL, results));
            }
        });
    });
}

module.exports = pool;
module.exports.querySQL = querySQL;
module.exports.execSQL = execSQL;
